﻿using Lamex.Common;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;

namespace Lamex.Main
{
    public partial class UpdateForm : Form
    {
        LocalInfo localInfo = new LocalInfo();
        public List<Lamex.Common.LocalInfo.RemoteInfo> UpdateVerList { get; set; }
        #region 让窗体变成可移动
        [DllImport("user32.dll")]
        public static extern bool ReleaseCapture();
        [DllImport("user32.dll")]
        public static extern bool SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam);

        [DllImport("User32.dll")]
        private static extern IntPtr WindowFromPoint(Point p);

        public const int WM_SYSCOMMAND = 0x0112;
        public const int SC_MOVE = 0xF010;
        public const int HTCAPTION = 0x0002;
        private IntPtr moveObject = IntPtr.Zero;    //拖动窗体的句柄

        private void PNTop_MouseDown(object sender, MouseEventArgs e)
        {
            if (moveObject == IntPtr.Zero)
            {
                if (this.Parent != null)
                {
                    moveObject = this.Parent.Handle;
                }
                else
                {
                    moveObject = this.Handle;
                }
            }
            ReleaseCapture();
            SendMessage(moveObject, WM_SYSCOMMAND, SC_MOVE + HTCAPTION, 0);
        }

        #endregion
        public UpdateForm()
        {
            InitializeComponent();
            localInfo.LoadXml();//当前版本信息
            UpdateVerList = GetServer(@"\\tx-fs8\tx-fs\TX-Public\TX-MFG\MES\LamexMES\Updater\Server.xml");//服务器路径
            CheckVer(localInfo.LocalVersion);//本地版本和服务器版本对比           
        }
        public  bool _Update()
        {
            bool ret = false;      
            if (UpdateVerList.Count > 0)
            {
                //显示更新内容
                foreach (var item in UpdateVerList[UpdateVerList.Count - 1].VersionDesc.Split('$'))
                {
                    this.lblContent.Text = this.lblContent.Text + item + Environment.NewLine;
                }
                this.ShowDialog();
            }
                     
            return ret;

        }
        /// <summary>
        /// 校验程序版本号
        /// </summary>
        /// <param name="LocalVer">当前本地版本信息</param>
        /// <param name="RemoteVer">服务器端版本信息</param>
        /// <returns></returns>
        private void CheckVer(String LocalVer)
        {
            String[] Local = LocalVer.Split('.');
            List<Lamex.Common.LocalInfo.RemoteInfo> list = new List<Lamex.Common.LocalInfo.RemoteInfo>();
            foreach (var item in UpdateVerList)
            {
                String[] Remote = item.ReleaseVersion.Split('.');
                for (int i = 0; i < Local.Length; i++)
                {
                    if (Int32.Parse(Local[i]) < Int32.Parse(Remote[i]))
                    {
                        list.Add(item);
                        break;
                    }
                    else if (Int32.Parse(Local[i]) == Int32.Parse(Remote[i]))
                    {
                        continue;
                    }
                    else
                    {
                        break;
                    }
                }
            }
            UpdateVerList = list;
           
        }
        /// <summary>
        /// 获取更新的服务器端的数据信息
        /// </summary>
        /// <param name="url">自动更新的URL信息</param>
        /// <returns></returns>
        private static List<Lamex.Common.LocalInfo.RemoteInfo> GetServer(String url)
        {
            List<Lamex.Common.LocalInfo.RemoteInfo> list = new List<Lamex.Common.LocalInfo.RemoteInfo>();
           // XmlReader xml = XmlReader.Create(url);
            XmlDocument xdoc = new XmlDocument();
            xdoc.Load(url);
            var root = xdoc.DocumentElement;
            var listNodes = root.SelectNodes("/ServerUpdate/item");
            foreach (XmlNode item in listNodes)
            {
                Lamex.Common.LocalInfo.RemoteInfo remote = new Lamex.Common.LocalInfo.RemoteInfo();
                foreach (XmlNode pItem in item.ChildNodes)
                {
                    remote.GetType().GetProperty(pItem.Name).SetValue(remote, pItem.InnerText, null);
                }
                list.Add(remote);
            }
            return list;
        }
        private void BtnUpdateNow_Click(object sender, EventArgs e)
        {
            try
            {
              
                //文件复制移动
                string PathServer = @"\\tx-fs8\tx-fs\TX-Public\TX-MFG\MES\LamexMES\Updater\Bin";//服务器路径
                string PathLocal = Application.StartupPath;
                CopyDirectory(PathServer, PathLocal);
                IgnoreThisVersion();//更新本地版本信息
                this.Close();
            }
            catch 
            {
                this.Close();             
            }
           
        }
        //文件复制
        public void CopyDirectory(string srcPath, string destPath)
        {
            try
            {
                DirectoryInfo dir = new DirectoryInfo(srcPath);
                FileSystemInfo[] fileinfo = dir.GetFileSystemInfos();  //获取目录下（不包含子目录）的文件和子目录
                foreach (FileSystemInfo i in fileinfo)
                {
                    if (i is DirectoryInfo)     //判断是否文件夹
                    {
                        if (!Directory.Exists(destPath + "\\" + i.Name))
                        {
                            Directory.CreateDirectory(destPath + "\\" + i.Name);   //目标目录下不存在此文件夹即创建子文件夹
                        }
                        Thread.Sleep(1000);
                        CopyDirectory(i.FullName, destPath + "\\" + i.Name);    //递归调用复制子文件夹
                    }
                    else
                    {
                        Thread.Sleep(1000);
                        File.Copy(i.FullName, destPath + "\\" + i.Name, true);      //不是文件夹即复制文件，true表示可以覆盖同名文件
                    }
                }
            }
            catch (Exception e)
            {
                throw;
            }
        }
        //更新本地版本信息
        public void IgnoreThisVersion()
        {
            var item = UpdateVerList[UpdateVerList.Count - 1];
            localInfo.LastUdpate = item.ReleaseDate;
            localInfo.LocalVersion = item.ReleaseVersion;
            localInfo.SaveXml();
        }
    }
}
